package org.huiway.huipicturebackend.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.huiway.huipicturebackend.common.BaseResponse;
import org.huiway.huipicturebackend.common.ResultUtils;
import org.huiway.huipicturebackend.exception.BusinessException;
import org.huiway.huipicturebackend.exception.ErrorCode;
import org.huiway.huipicturebackend.utils.mail.MailMsg;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.Duration;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 邮箱验证码以及本地验证码接口
 */
@RestController
@RequestMapping("/code")
@Slf4j
public class CodeController {
    @Resource
    private MailMsg mailMsg;
    @Resource
    private RedisTemplate<String, String> redisTemplate;


    /**
     * 发送邮箱验证码
     * 前端邮箱拼接 -> ${encodeURIComponent(param0)}
     *
     * @param email
     * @return
     */
    @GetMapping(value = "sendEmail/{email}")
    public BaseResponse<Object> sendMail(@PathVariable String email) {
        log.info("邮箱码 :{}", email);
        //从redis中取出验证码信息
        String code = redisTemplate.opsForValue().get(email);
        log.info("code:{}", code);
        if (!StrUtil.isEmpty(code)) {
            return ResultUtils.success(email + ":" + code + "已存在，还未过期");
        }
        try {
            boolean mail = mailMsg.mail(email);
            if (mail) {
                return ResultUtils.success("发送成功");
            }
            // 使用error而非success
            return (BaseResponse<Object>) ResultUtils.error(ErrorCode.OPERATION_ERROR, "发送失败");
        } catch (MessagingException e) {
            log.error("邮件发送异常", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "邮件发送异常: " + e.getMessage());
        }
    }

    /**
     * 本地创建生成验证码
     *
     * @return
     */
    @RequestMapping("/get/captcha")
    public void getCaptcha(HttpServletResponse response) throws IOException {
        // 1. 生成验证码
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(128, 50,4,15);
        String uuid = UUID.randomUUID().toString().replace("-", "");

        // 2. 写入响应流（不存本地）
        response.setContentType("image/png");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        lineCaptcha.write(response.getOutputStream());

        // 3. 存验证码到 Redis
        redisTemplate.opsForValue().set(uuid, lineCaptcha.getCode(), Duration.ofMinutes(5));

        // 4. 把 uuid 通过响应头返回
        response.setHeader("Captcha-Key", uuid);

    }


}
